package com.cn.remote;

import com.cn.common.Pair;
import com.cn.common.ResponseFuture2;
import com.cn.common.processor.INettyRequestProcessor;
import com.cn.msg.Message;
import io.netty.channel.ChannelHandlerContext;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Semaphore;

public abstract class AbStractNetty {

    /**
     * 假设该参数是1000，那么允许最大有1000个线程调用，防止耗尽系统资源
     * 当第一个线程调用的时候，该参数变为999
     * 当第二个线程调用的时候，该参数变为998,
     * ……
     * 当第一个线程调用完成的时候，该参数+1，变为999
     * 当第二个线程调用完成的时候，该参数+1，变为1000
     */
    public final Semaphore semaphoreAsync;
    public Map<Integer, Pair<INettyRequestProcessor, ExecutorService>> processTables = new HashMap<>();
    protected static ConcurrentMap<Long, ResponseFuture2> responseFutureTables = new ConcurrentHashMap<>(128);

    //处理回调
    public ExecutorService callbackExecutor = null;

    public AbStractNetty(int asyncNum) {
        asyncNum = asyncNum <= 0 ? 100 : asyncNum;
        this.semaphoreAsync = new Semaphore(asyncNum, true);
    }

    public void process(Message message, ChannelHandlerContext ctx) {
        if (null != message) {
            if (message.getFlag() == 0) {
                processResponse(message, ctx);

            } else {
                processRequest(message, ctx);

            }
        }
    }

    public void processRequest(Message message, ChannelHandlerContext ctx) {
        Pair<INettyRequestProcessor, ExecutorService> processor = this.processTables.get((int) message.getNettyRequestWrapperCode());
        if (processor != null) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Message response = processor.getObject1().process(message, ctx);
                        if (response != null) {
                            response.setFlag((byte) 0);
                            ctx.writeAndFlush(response);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            processor.getObject2().submit(runnable);
        }
    }

    /**
     * 响应请求
     *
     * @param message
     * @param ctx
     */
    public void processResponse(Message message, ChannelHandlerContext ctx) {
        if (message.getOpaque() > 0) {
            ResponseFuture2 responseFuture2 = this.responseFutureTables.get(message.getOpaque());
            try {
                if (responseFuture2 != null) {
                    responseFuture2.putResponse(message.getByteBodys());
                    if (responseFuture2.getInvokeCallback() != null) {
                        //如果是异步调用
                        executCallback(responseFuture2);
                    } else {
                        responseFuture2.release();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //移除标识位
                this.responseFutureTables.remove(message.getOpaque());
            }
        }
    }

    public void executCallback(ResponseFuture2 responseFuture2) {
        this.callbackExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    responseFuture2.executInvokeCallback();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    responseFuture2.release();
                }
            }
        });
    }

    //解码
    public Message decodeBody(Message message) {
        return message.setBody(new String(message.getByteBodys(), Charset.forName("utf-8")));
    }

    public void cleanProcessor() {
        this.processTables.clear();
    }

    public ExecutorService getCallbackExecutor() {
        return callbackExecutor;
    }
}
